﻿using System;
using TaskManager.Domain.BusinessObjects;
using TaskManager.Domain.Exceptions;
using TaskManager.Domain.Repositories;

namespace TaskManager.Domain.Services
{
    /// <summary>
    /// Provides method for <seealso cref="Project"/> deletion
    /// </summary>
    internal class ProjectDeleteService : IProjectDeleteService
    {
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ProjectDeleteService));

        private readonly IProjectRepository _projectRepository;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="projectRepository">Project repository</param>
        public ProjectDeleteService(IProjectRepository projectRepository)
        {
            _projectRepository = projectRepository;

            if(Log.IsDebugEnabled) Log.Debug("Created ProjectDeleteService");
        }

        /// <summary>
        /// Deletes a project
        /// </summary>
        /// <param name="project">Project</param>
        /// <exception cref="UserActionFailureException">Thrown if project can not be deleted</exception>
        public void Delete(Project project)
        {
            if (Log.IsDebugEnabled) Log.Debug("Deleting project.Name=[" + project.Name + "]");

            Tuple<bool, string> result = ProjectValidationRules.PermitDelete(project);

            if(!result.Item1)
                throw new UserActionFailureException(result.Item2);

            _projectRepository.Delete(project.Id);
            if (Log.IsDebugEnabled) Log.Debug("Project deleted");
        }

        /// <summary>
        /// Deletes a project
        /// </summary>
        /// <param name="projectId">Project identifier</param>
        /// <exception cref="UserActionFailureException">Thrown if project can not be deleted</exception>
        public void Delete(int projectId)
        {
            Project project = _projectRepository.Find(projectId);

            if (Log.IsDebugEnabled) Log.Debug("Deleting project.Name=[" + project.Name + "]");

            Tuple<bool, string> result = ProjectValidationRules.PermitDelete(project);

            if (!result.Item1)
                throw new UserActionFailureException(result.Item2);

            _projectRepository.Delete(projectId);
            if (Log.IsDebugEnabled) Log.Debug("Project deleted");
        }
    }
}